package com.test.daily.leetcode.y2021.m12.day1207;

/**
 * ColorBorder
 *
 * @author Tom on 2021/12/7
 */
public class Code01_ColorBorder {

    public static void main(String[] args) {
        Code01_ColorBorder cc = new Code01_ColorBorder();
        int[][] grid = new int[][]{{1, 2, 2}, {2, 3, 2}};
        int row = 0, col = 1, color = 3;
        int[][] ans = cc.colorBorder(grid, row, col, 3);
        for (int i = 0; i < ans.length; i++) {
            for (int j = 0; j < ans[0].length; j++) {
                System.out.print(ans[i][j] + "");
            }
            System.out.println();
        }
    }

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        int[][] ans = grid;
        int M = grid.length - 1;
        int N = grid[0].length - 1;
        colored(grid, row, col, color, M, N, ans);

        return ans;
    }

    void colored(int[][] grid, int row, int col, int color, int M, int N, int[][] ans) {
        if (row < 0 || row > M || col < 0 || col > N) {
            return;
        }
        if (isBorder(row, col, grid, M, N) && grid[row][col] != Integer.MIN_VALUE) {
            ans[row][col] = color;
            grid[row][col] = Integer.MIN_VALUE;
        }
        if (row - 1 >= 0 && grid[row][col] != grid[row - 1][col]) {
            colored(grid, row - 1, col, color, M, N, ans);
        }
        if (col - 1 >= 0 && grid[row][col] != grid[row][col - 1]) {
            colored(grid, row, col - 1, color, M, N, ans);
        }
        if (row + 1 <= M && grid[row][col] != grid[row + 1][col]) {
            colored(grid, row + 1, col, color, M, N, ans);
        }
        if (col + 1 <= N && grid[row][col] != grid[row][col + 1]) {
            colored(grid, row, col + 1, color, M, N, ans);
        }
    }

    boolean isBorder(int row, int col, int[][] grid, int m, int n) {
        return row == 0 || col == 0 || row == m || col == n
                || (grid[row][col] != grid[row - 1][col]
                && grid[row][col] != grid[row + 1][col]
                && grid[row][col] != grid[row][col + 1]
                && grid[row][col] != grid[row][col - 1]);
    }
}
